import React, {useEffect, useState} from 'react';
import {Link, useHistory} from "react-router-dom";
import {Modal,List, Drawer, Button, Toast,PullToRefresh,InputItem,DatePicker} from 'antd-mobile';



import Txt from "../../../components/txt/Txt";

import './userHomeList.less';
import man from '../../../libs/img/user/man.png';
import woman from '../../../libs/img/user/woman.png';
import http from "../../../model/http"; 
import Header from "../../../components/header/Header";
import {dateFormat} from '../../../model/code';
import More from "./more/index"
let page = 1;
let list=[]
let param = {}
const h = document.documentElement.clientHeight - 40;

function UserList() { 
    
    const history = useHistory();
    // const [list,setList] = useState([]);
    const [load,setLoad] = useState(false);
    const [listCount,setListCount] = useState(0)
    const [sliderData,setSliderData] = useState([])

    const [open ,setOpen] =useState(false)

    const [jurisdiction, setJurisdiction] = useState({})
    
    // let data= [
    //     {
    //         title:"营销词1",
    //         titleId:"1",
    //         type:"1",
    //         list:[
    //             {
    //                 id:"1",
    //                 name:"0"
    //             },
    //             {
    //                 id:"2",
    //                 name:"100"
    //             },
               
    //         ]
    //     },


    //     {
    //         title:"营销词1",
    //         titleId:"1",
    //         type:"2",
    //         list:[
    //             {
    //                 id:"1",
    //                 value:"0"
    //             },
    //             {
    //                 id:"2",
    //                 value:"100"
    //             },
               
    //         ]
    //     },
        
    //     {
    //         title:"日期选择",
    //         titleId:"3",
    //         type:"3",
    //         start:new Date(),
    //         end:new Date(),
    //         list:[
    //             {
    //                 id:"1",
    //                 value:"0"
    //             },
    //             {
    //                 id:"2",
    //                 value:"100"
    //             },
               
    //         ]
    //     },

    //     {
    //         title:"日期选择",
    //         titleId:"4",
    //         type:"3",
    //         start:new Date(),
    //         end:new Date(),
    //         list:[
    //             {
    //                 id:"1",
    //                 value:"0"
    //             },
    //             {
    //                 id:"2",
    //                 value:"100"
    //             },
               
    //         ]
    //     },
     
        
    //  ]

    let [filterData,setFilterData] = useState([])
    
    

    const getList = ()=>{
        (async ()=>{
        setLoad(true);

        if( history.location.state.flag == 4 ){

            const _list = await http.post_all('/usercenter/customerlist2',param)
            setTimeout(()=>{setLoad(false)},800)
            setListCount(_list.allcount)
            if(!_list.data.length) return;
            page++;    
            param.page =page
            console.log("page",page)
            list = [...list,..._list.data];

            // const _list = await http.post('/usercenter/customerlist',param)
            // setTimeout(()=>{setLoad(false)},800)
            // setListCount(_list.allcount)
            // if(!_list.data.length) return
            // page++
            // param.page =page
            // console.log("page",page)
            // list = [...list,..._list.data]




        }else{
            const _list = await http.post('/usercenter/customerlist',param)
            setTimeout(()=>{setLoad(false)},800)
            setListCount(_list.allcount)
            if(!_list.data.length) return
            page++
            param.page =page
            console.log("page",page)
            list = [...list,..._list.data]

        }
        
       

        })()
        
    }

    const getSliderData=async ()=>{
        //http://wxwork.gzsg.cn/wxwork/customersearch/getCondition?searchHosId=1&userId=xxx&managerId=xxx&hosId=1
          
        const slderList = await http.post('/customersearch/getCondition',{
            searchHosId:"1"
        })
        console.log("setList",slderList.resultData)
        slderList.resultData.forEach(item=>{
            if(item.type == 3){
                item.start=new Date()
                item.end=new Date()
            }
        })
        setFilterData(slderList.resultData)

    }

    const done = ()=>{
        console.log("done")
        setOpen(true)
        getSliderData()
    }

    const sureSubmit=()=>{

        let myFilterData = JSON.parse(JSON.stringify(filterData))
       
        let newArr = []
        
        myFilterData.forEach( m=>{
            if(m.type == 2 ){
               if(m.hasOwnProperty("start")||m.hasOwnProperty("end") ){
                  delete m.list
                  newArr.push(m)
               }
            }
             
            if( m.type == 3 ){       
                m.start = (m.start+"").slice(0,10)
                m.end = (m.end+"").slice(0,10)
                delete m.list
                newArr.push(m)
            }



            if(m.type == 1){
                let btnArrList=[]
                m.list.forEach( k=>{
                    if(k.selected){
                        btnArrList.push( k.value )
                    }
                   
                } )
                m.selectedData=btnArrList.join(",")

                if(btnArrList.length>0){
                    delete m.list
                    newArr.push(m)
                }
             
            }
        } )
        
        console.log("finalDate",newArr)



        setOpen(false)
        page=1
        list=[]
        setListCount(0)

        param={
            flag:1,
            page:page,
            items:10,  
            filterData:newArr
        }

        setTimeout(()=>{
           getList()
        },100)
       


    }

    const currentExchange =(id,item)=>{
        console.log("id",id) //外层id
        console.log("item",item) // 内层数组
        
        let list= JSON.parse(JSON.stringify(filterData))
        list.forEach((n)=>{ //外层
            if(n.type == 3){
                n.start=new Date(n.start) 
                n.end = new Date(n.end)
            }
           

            n.list.forEach((m)=>{ //内层
                 if(n.titleId == id){
                     if(m.id == item.id){
                         if(m.selected){
                             m.selected= false
                         }else{
                             m.selected=true
                         }
                     }
                 }
            })
        })
        console.log("filterData",list) // 内层数组
        setFilterData(list)
    }

    const reSet=()=>{
        // let list= JSON.parse(JSON.stringify(filterData))
        // list.forEach((n)=>{ //外层
        //     n.list.forEach((m)=>{ //内层           
        //             m.selected=false 
        //     })
        // })
        // console.log("filterData",list) // 内层数组
        // setFilterData(list)

        getSliderData()
 

    }

    const type2Change1 =(v,id)=>{
        console.log("id",id)
        let list= JSON.parse(JSON.stringify(filterData))
        list.forEach((n)=>{ //外层
            if(n.type == 3){
                n.start=new Date(n.start) 
                n.end = new Date(n.end)
            }
            
            if(n.type == 2){
                if(n.titleId == id){
                    if(!n.end){ n.end= parseInt(n.list[1].value)||0  }
                    if(parseInt(v)>parseInt(n.end)){
                        n.start =parseInt(v) ||0
                        n.end =parseInt(v) ||0
                        
                        if(parseInt(v)> parseInt(n.list[1].value)){
                           n.start= parseInt(n.list[1].value)||0
                           n.end= parseInt(n.list[1].value)||0
                        }

                    }else{
                        n.start =parseInt(v) ||0
                        if(parseInt(v)> parseInt(n.list[1].value)){
                            n.start= parseInt(n.list[1].value) ||0
                            n.end= parseInt(n.list[1].value) ||0
                         }
 
                    }

                    

                }
            }
           
           
        })
        console.log("filterData",list) // 内层数组
        setFilterData(list)

    }

    const type2Change2 =(v,id)=>{
        console.log("id",id)
        let list= JSON.parse(JSON.stringify(filterData))
        list.forEach((n)=>{ //外层
            if(n.type == 3){
                n.start=new Date(n.start) 
                n.end = new Date(n.end)
            }
            if(n.type == 2){
                if(n.titleId == id){
                    n.start =parseInt(n.start) || 0
                    if(parseInt(v)<parseInt(n.start)){
                        n.end =parseInt(n.start) || 0
                        
                        if(parseInt(v)> parseInt(n.list[1].value)){
                            n.end= parseInt(n.list[1].value) || 0
                           
                         }
 

                    }else{
                        n.end =parseInt(v) || 0
                        if(parseInt(v)> parseInt(n.list[1].value)){
                            n.end= parseInt(n.list[1].value) || 0
                         }
 
                    }
                }
            }

           
           
           
        })
        console.log("filterData",list) // 内层数组
        setFilterData(list)
    }

    const type3Change1 =(v,id)=>{
        console.log("id",id)
        let list= JSON.parse(JSON.stringify(filterData))
        list.forEach((n)=>{ //外层
            if(n.type == 3){
                if(n.titleId == id){
        
                    // n.start=new Date(dateFormat(v,'yyyy-MM-dd')) 
                    // n.end = new Date(n.end)
                    
                    if( new Date(dateFormat(v,'yyyy-MM-dd')).getTime() >  new Date(n.end).getTime() ){
                      
                            n.start=new Date(dateFormat(v,'yyyy-MM-dd')) 
                            n.end =new Date(dateFormat(v,'yyyy-MM-dd')) 

                     
                      

                    }else{
                         n.start=new Date(dateFormat(v,'yyyy-MM-dd')) 
                         n.end = new Date(n.end)
                    }



                }else{
                    n.start=new Date(n.start) 
                    n.end = new Date(n.end)
                }
               
            }

          
        })
        

        console.log("filterData",list) // 内层数组
        setFilterData(list)
    }

    const type3Change2 =(v,id)=>{
        console.log("id",id)
        let list= JSON.parse(JSON.stringify(filterData))
        list.forEach((n)=>{ //外层
            if(n.type == 3){
                if(n.titleId == id){
          
                    // n.end=new Date(dateFormat(v,'yyyy-MM-dd')) 
                    // n.start = new Date(n.start)
                     
                    if( new Date(dateFormat(v,'yyyy-MM-dd')).getTime() <  new Date(n.start).getTime() ){
                       
                             n.start=new Date(dateFormat(n.start,'yyyy-MM-dd')) 
                             n.end =new Date(dateFormat(n.start,'yyyy-MM-dd')) 
                       
                       
                       


                   }else{
                        n.end=new Date(dateFormat(v,'yyyy-MM-dd')) 
                        n.start = new Date(n.start)
                   }

 


                }else{
                    n.start=new Date(n.start) 
                    n.end = new Date(n.end)
                }
            }

           
           
        })
        console.log("filterData",list) // 内层数组
        setFilterData(list)
    }

    useEffect(()=>{  
        setJurisdiction(sessionStorage.getItem('doctorJurisdiction')?JSON.parse(sessionStorage.getItem('doctorJurisdiction')):'')
        
        param={
            flag:history.location.state.flag, 
            // flag:1,
            page:page,
            items:10,  
        }
        list=[]
        list.length || getList();

        return ()=>{
        
        page=1
        }
        // eslint-disable-next-line
    },[])
      
    const toDeails=(item)=>{
       history.push(`/user/details?isBind=${1}&outUserId=${item.customerCrmId}&entryIsHome=${1}`, item); //跳转到客户详情页面
    }
    // const row = (rowData, sectionID, rowID) => {
    //     return (
    //         <div key={rowID} className='userList-row g-flex g-x-between g-mt32'
    //              onClick={toDeails.bind(this,rowData,outUserId,isBindOutUesr)}
    //              style={{padding: '0.25rem 0.2rem', backgroundColor: '#FFFFFF'}}>
    //                 <div className=' g-flex' >
    //                     <img src={rowData.sex=='1'?woman:man} style={{width:'1rem',height:'1rem'}} className='g-round' alt="UserImg"/>
    //                     <div className='g-ml20 g-f24 g-c-999'>
    //                         <p className='g-f30 g-c-333 '>
    //                             <span style={{fontSize:'0.32rem',fontWeight:'bold'}}>{rowData?.customerName}</span>
    //                         </p>
    //                         {/*<p className='g-f26 g-mt15'>顾客id：<span className='g-f24'>{rowData?.customerCrmId}</span></p>*/}
    //                         <p className='g-mt24'>卡号：<span>{rowData?.mzcode}</span></p>
    //                         <p className='g-mt12' style={{lineHeight:'0.4rem'}}>所属咨询：{rowData?.xcname}</p>
    //                         <p className='g-mt12' style={{lineHeight:'0.4rem'}}>开发人：{rowData?.dwname}</p>
    //                         {/*<p className='g-f30 g-mt10'> <span style={{ color: '#FF6E27' }}>{parseInt(rowID) +1}</span></p>*/}
    //                     </div>
    //                 </div>
    //         </div>
    //     );
    // };

   

    return (
        <div className='v-user-userHomeList'>
            {
                (history.location.state.flag == 4)
                //   &&
                // ( jurisdiction.authority == 1 || jurisdiction.authority == 2 || jurisdiction.authority == 9)
                ? (
                    <More done={done}></More>
                ) :null
            }
            
            {/* <More done={done}></More> */}
            
            {/* 弹框 */}
            { 
               open ? (
                    <div>
                    <div onClick={ ()=>{ 
                        setOpen(false) 
                        
                     } } className='my_masker'>
                    </div>
                    <div className='masker_content'>
                        <div className='scroll'>
                        {
                            filterData.map((item,index)=>(
                                <div className='masker_item' style={{width:'100%'}}>
                                     <div className='title'>{item.title}</div>
                                       {
                                           item.type==1 ? (
                                                <div className='tagBox'> 
                                                {
                                                    item.list.map((item1,index)=>(
                                                    <div className={ item1.selected?'active' :'tag' } onClick={(  )=>{ currentExchange(item.titleId,item1) } }   >{item1.name}</div>
                                                    ))
                                                }                 
                                            </div>
                                           ) : null
                                       }

                                       {
                                           item.type==2 ? (
                                                <div className='tagBox'> 
                                                <div style={{flex:1}}>
                                                    <InputItem type='number'   
                                                        value={ item.start}  
                                                        placeholder = {'最小值'+item.list[0].value }
                                                        onChange={(v) => {  type2Change1(v,item.titleId)  }} 
                                                    /> 
                                                </div>
                                                <div style={{marginTop:"12px"}}>至</div>
                                                <div style={{flex:1,}}>
                                                <InputItem type='number'   
                                                    value={ item.end}  
                                                    placeholder = {'最大值'+item.list[1].value }
                                                    onChange={(v) => { type2Change2(v,item.titleId)}} 
                                                /> 
                                                </div>
                                                 
                                                 

                                            </div>
                                           ) : null
                                       }

                                           {
                                            item.type==3 ? (
                                                <div className='tagBox'> 
                                                <div style={{flex:1}}>
                                                <DatePicker mode="date" value={item.start}  onChange={d1=>{  type3Change1(d1,item.titleId) }}>  
                                                    <List.Item arrow="horizontal"></List.Item>
                                                    </DatePicker>  
                                                </div>
                                                <div style={{marginTop:"12px"}}>至</div>
                                                <div style={{flex:1,}}>
                                                <DatePicker mode="date" value={item.end}    onChange={d2=>{ type3Change2(d2,item.titleId)  }}>  
                                                    <List.Item arrow="horizontal"></List.Item>
                                                    </DatePicker> 
                                                </div>
                                                 
                                                 

                                            </div>
                                           ) : null
                                       }



                                    

                                </div>
                            ))
                        } 

                        </div> 

                        <div className='masker_btn'>
                            <div onClick={()=>{ reSet() }} style={{textAlign:'center',lineHeight:'34px', color:'black',width:'90px',height:'34px',borderRadius:'60px',border:'1px solid #c8c8c8'}}>重置</div>
                            <div onClick={()=>{ sureSubmit()   } } style={{marginLeft:'12px', textAlign:'center',lineHeight:'34px', color:'#ffffff',backgroundColor:'#108ee9', width:'90px',height:'34px',borderRadius:'60px',border:'1px solid #108ee9'}}>确定</div>
                        </div>
                    </div>
                </div>

               ) : null
            
            }
           
           
            <div className='body-background-div'></div>
            <PullToRefresh direction='up' onRefresh={getList} refreshing={load} style={{height:h, overflow:'auto',fontSize:"14px"}}>
                 
                {list.map((item,idx)=>(
                    <div key={idx} className='userList-row g-flex g-x-between g-mt32'
                    onClick={toDeails.bind(this,item)}
                    style={{padding: '0.25rem 0.2rem', backgroundColor: '#FFFFFF'}}>
                        <div className='g-flex' >
                            <img src={item.sex=='1'?woman:man} style={{width:'1rem',height:'1rem'}} className='g-round' alt="UserImg"/>
                            <div className='g-ml20 g-f24 g-c-999'>
                                <p className='g-f30 g-c-333 '>
                                    <span style={{fontSize:'0.32rem',fontWeight:'bold'}}>{item?.customerCrmName}</span>
                                </p> 
                                <p className='g-mt24'>卡号：<span>{item?.mzcode}</span></p>
                                <p className='g-mt12' style={{lineHeight:'0.4rem'}}>所属咨询：{item.xcname?item.xcname:'暂无'}</p>
                                <p className='g-mt12' style={{lineHeight:'0.4rem'}}>开发人：{item.dwname?item.dwname:'暂无'}</p> 
                            </div>
                        </div> 
                        
                    </div>
                    
                ))}
                {list.length >= listCount? <div className='test-color'>暂无更多数据</div> : ''}
            </PullToRefresh>
            
          


            <Header/>
           
            
            {
                // list.length>0&& (
                // <div style={{marginTop:'0.32rem'}}> 
                //     <ListView
                //         dataSource={dataSource}
                //         renderFooter={() => (<div style={{ padding: 30, textAlign: 'center' }}>
                //             {
                //                 !hasMore?'加载完毕，没有更多数据了~':(
                //                     isLoading && 'Loading...'
                //                 )
                //             }
                //         </div>)}
                //         renderRow={row}
                //         useBodyScroll
                //         onEndReachedThreshold={100}
                //         onEndReached={onEndReached}
                //         pageSize={10}
                //     />
                // </div>
                // )
            }

        </div>
    )
}
export default UserList;

// "customerCrmId": "20160504020458953000", 
// "sex": 1, 
// "xcname": "高慧清", 
// "dwname": "王进福", 
// "mzcode": "160215111", 
// "age": 21, 
// "customerCrmName": "李甜"